<template>
    <div class="add">
        <el-dialog :title="!department.id?'添加机构':'编辑机构'" :visible="optVisible" @close="hide" width="400px">
            <el-form ref="form" :model="formData" label-width="74px">
                <el-form-item label="机构名称:" :class="{'m-b-20':!isExist}">
                    <el-input v-model="formData.name" :maxlength=20></el-input>
                    <div class="rename-msg">{{ errorMsg }}</div>
                </el-form-item>
            </el-form>
            <div class="optBtn">
                <el-button class="w-80" @click="hide">取消</el-button>
                <el-button type="primary" class="w-80" :disabled="isExist" :loading="loading" @click="comfirm">确定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'add',
    props: {
        orgId: String,
        orgLabel: String,
        department: Object,
        optVisible: Boolean
    },
    data () {
        return {
            errorMsg: '',
            formData: {},
            isExist: false,
            loading: false
        }
    },
    created () {
        if (this.department.id) {
            this.getDetail();
        }
    },
    methods: {
        getDetail () {
            this.formData = {
                id: this.department.id,
                name: this.department.name
            };
        },
        comfirm () {
            const isEdit = Boolean(this.department.id);
            const url = isEdit ? `/orginfo/department/${this.department.id}` : '/orginfo/department';
            const method = isEdit ? 'put' : 'post';
            const message = isEdit ? '编辑成功！' : '新增成功！';
            const params = isEdit ? {
                name: this.formData.name
            } : {
                name: this.formData.name,
                groupId: this.orgId,
                orgLabel: this.orgLabel
            };

            this.loading = true;
            this.$x[method](url, params).then(({ success = true, errmsg }) => {
                if (success) {
                    this.$x.toast.success(message);
                    this.$emit('update');
                    this.hide();
                } else {
                    this.errorMsg = errmsg;
                }
            }).finally(() => {
                this.loading = false;
            })
        },
        hide () {
            this.$emit('update:optVisible', false);
        }
    }
}
</script>

<style scoped lang="scss">
    .rename-msg {
        height: 30px;
        color: #ed4040;
        font-size: .12rem;
    }

    .optBtn {
        height: 32px;
        display: flex;
        justify-content: center;
        /deep/ {
            .el-button {
                float: left;
                width: 80px;
            }
        }
    }

    /deep/ .el-form-item--small.el-form-item {
        margin-bottom: 0;
    }

    /deep/ .el-dialog__body {
        padding: .3rem .4rem .2rem;
    }
</style>
